using B.S.Data.MES.API.Models;
using B.S.Data.MES.API.Services;
using B.S.Domain.Dto.AICustomerServiceDTO;
using B.S.Requst;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace B.S.Data.MES.API.Controllers
{
    /// <summary>
    /// AI智能助手控制器 - 集成科大讯飞API
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AIAssistantController : ControllerBase
    {
        private readonly IXunFeiService _xunFeiService;
        private readonly IDataQueryService _dataQueryService;
        private readonly ILogger<AIAssistantController> _logger;

        public AIAssistantController(
            IXunFeiService xunFeiService,
            IDataQueryService dataQueryService,
            ILogger<AIAssistantController> logger)
        {
            _xunFeiService = xunFeiService;
            _dataQueryService = dataQueryService;
            _logger = logger;
        }

        /// <summary>
        /// AI智能对话接口
        /// </summary>
        /// <param name="request">对话请求</param>
        /// <returns>AI回复</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<AIAssistantResponse>> Chat([FromBody] AIAssistantRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Message))
                {
                    return new APIRequst<AIAssistantResponse>
                    {
                        Code = RequstCode.失败,
                        Msg = "请输入您的问题",
                        Data = null!
                    };
                }

                // 记录用户IP和设备信息
                var clientIP = GetClientIP();
                var deviceInfo = GetDeviceInfo();
                
                _logger.LogInformation("AI对话请求 - IP: {IP}, 设备: {Device}, 消息: {Message}", 
                    clientIP, deviceInfo, request.Message);

                // 如果没有会话ID，生成一个新的
                if (string.IsNullOrEmpty(request.SessionId))
                {
                    request.SessionId = Guid.NewGuid().ToString("N");
                }

                // 调用智能助手服务
                var response = await _xunFeiService.SmartChatAsync(request);

                return new APIRequst<AIAssistantResponse>
                {
                    Code = RequstCode.成功,
                    Msg = "对话成功",
                    Data = response
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AI对话异常: {Message}", ex.Message);
                return new APIRequst<AIAssistantResponse>
                {
                    Code = RequstCode.失败,
                    Msg = $"对话失败: {ex.Message}",
                    Data = new AIAssistantResponse
                    {
                        Response = "抱歉，AI助手暂时无法响应，请稍后再试或联系人工客服。",
                        SessionId = request.SessionId,
                        Suggestions = new List<string> { "重新尝试", "联系人工客服", "查看帮助文档" }
                    }
                };
            }
        }

        /// <summary>
        /// 简单聊天接口（不集成数据查询）
        /// </summary>
        /// <param name="message">用户消息</param>
        /// <param name="sessionId">会话ID</param>
        /// <returns>AI回复</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<string>> SimpleChat([FromBody] string message, [FromQuery] string? sessionId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(message))
                {
                    return new APIRequst<string>
                    {
                        Code = RequstCode.失败,
                        Msg = "请输入您的问题",
                        Data = string.Empty
                    };
                }

                var response = await _xunFeiService.ChatAsync(message);

                return new APIRequst<string>
                {
                    Code = RequstCode.成功,
                    Msg = "对话成功",
                    Data = response
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "简单对话异常: {Message}", ex.Message);
                return new APIRequst<string>
                {
                    Code = RequstCode.失败,
                    Msg = $"对话失败: {ex.Message}",
                    Data = "抱歉，AI助手暂时无法响应，请稍后再试。"
                };
            }
        }

        /// <summary>
        /// 数据查询接口
        /// </summary>
        /// <param name="question">查询问题</param>
        /// <returns>查询结果</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<DataQueryResult>> QueryData([FromBody] string question)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(question))
                {
                    return new APIRequst<DataQueryResult>
                    {
                        Code = RequstCode.失败,
                        Msg = "请输入查询问题",
                        Data = null!
                    };
                }

                var result = await _dataQueryService.QueryDataByQuestion(question);

                return new APIRequst<DataQueryResult>
                {
                    Code = result.Success ? RequstCode.成功 : RequstCode.失败,
                    Msg = result.Success ? "查询成功" : "查询失败",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "数据查询异常: {Message}", ex.Message);
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败: {ex.Message}",
                    Data = new DataQueryResult
                    {
                        Success = false,
                        Answer = "查询出现异常，请稍后再试。",
                        ErrorMessage = ex.Message
                    }
                };
            }
        }

        /// <summary>
        /// 获取工单信息
        /// </summary>
        /// <param name="workCode">工单编号（可选）</param>
        /// <returns>工单信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<DataQueryResult>> GetWorkOrders([FromQuery] string? workCode = null)
        {
            try
            {
                var result = await _dataQueryService.GetWorkOrderInfo(workCode);
                
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.成功,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询工单异常: {Message}", ex.Message);
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败: {ex.Message}",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 获取物料信息
        /// </summary>
        /// <param name="materialCode">物料编号（可选）</param>
        /// <returns>物料信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<DataQueryResult>> GetMaterials([FromQuery] string? materialCode = null)
        {
            try
            {
                var result = await _dataQueryService.GetMaterialInfo(materialCode);
                
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.成功,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询物料异常: {Message}", ex.Message);
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败: {ex.Message}",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 获取客户信息
        /// </summary>
        /// <param name="customerName">客户名称（可选）</param>
        /// <returns>客户信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<DataQueryResult>> GetCustomers([FromQuery] string? customerName = null)
        {
            try
            {
                var result = await _dataQueryService.GetCustomerInfo(customerName);
                
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.成功,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询客户异常: {Message}", ex.Message);
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败: {ex.Message}",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 获取仓库信息
        /// </summary>
        /// <param name="warehouseName">仓库名称（可选）</param>
        /// <returns>仓库信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<DataQueryResult>> GetWarehouses([FromQuery] string? warehouseName = null)
        {
            try
            {
                var result = await _dataQueryService.GetWarehouseInfo(warehouseName);
                
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.成功,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询仓库异常: {Message}", ex.Message);
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败: {ex.Message}",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 获取系统统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<APIRequst<DataQueryResult>> GetStatistics()
        {
            try
            {
                var result = await _dataQueryService.GetSystemStatistics();
                
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.成功,
                    Msg = "查询成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询统计异常: {Message}", ex.Message);
                return new APIRequst<DataQueryResult>
                {
                    Code = RequstCode.失败,
                    Msg = $"查询失败: {ex.Message}",
                    Data = null!
                };
            }
        }

        /// <summary>
        /// 健康检查
        /// </summary>
        /// <returns>健康状态</returns>
        [HttpGet]
        [AllowAnonymous]
        public APIRequst<object> HealthCheck()
        {
            try
            {
                var health = new
                {
                    Status = "Healthy",
                    Service = "AI智能助手",
                    Provider = "科大讯飞",
                    Timestamp = DateTime.Now,
                    Features = new[]
                    {
                        "智能对话",
                        "数据查询",
                        "项目信息集成",
                        "多轮对话支持"
                    }
                };

                return new APIRequst<object>
                {
                    Code = RequstCode.成功,
                    Msg = "AI助手服务运行正常",
                    Data = health
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "健康检查失败: {Message}", ex.Message);
                return new APIRequst<object>
                {
                    Code = RequstCode.失败,
                    Msg = $"健康检查失败: {ex.Message}",
                    Data = new { Status = "Unhealthy", Error = ex.Message }
                };
            }
        }

        /// <summary>
        /// 测试科大讯飞API连接
        /// </summary>
        /// <returns>测试结果</returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<APIRequst<object>> TestXunFeiConnection()
        {
            try
            {
                _logger.LogInformation("开始测试科大讯飞API连接");
                
                var testResponse = await _xunFeiService.ChatAsync("你好，这是一个连接测试");
                
                return new APIRequst<object>
                {
                    Code = RequstCode.成功,
                    Msg = "科大讯飞API连接测试成功",
                    Data = new 
                    { 
                        TestMessage = "你好，这是一个连接测试",
                        Response = testResponse,
                        Timestamp = DateTime.Now
                    }
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "科大讯飞API连接测试失败: {Message}", ex.Message);
                return new APIRequst<object>
                {
                    Code = RequstCode.失败,
                    Msg = $"科大讯飞API连接测试失败: {ex.Message}",
                    Data = new { Error = ex.Message, StackTrace = ex.StackTrace }
                };
            }
        }

        #region 辅助方法

        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        private string GetClientIP()
        {
            try
            {
                var ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                if (string.IsNullOrEmpty(ip) || ip == "::1")
                    ip = "127.0.0.1";
                return ip;
            }
            catch
            {
                return "unknown";
            }
        }

        /// <summary>
        /// 获取设备信息
        /// </summary>
        private string GetDeviceInfo()
        {
            try
            {
                var userAgent = HttpContext.Request.Headers["User-Agent"].ToString();
                return string.IsNullOrEmpty(userAgent) ? "unknown" : userAgent;
            }
            catch
            {
                return "unknown";
            }
        }

        #endregion
    }
}
